import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { precisionAdd, precisionMultiply } from '@/utils/precision'

/**
 * Health Store
 * 管理健康数据的状态和操作
 */
export const useTempShopStore = defineStore('tempShop', () => {
  const showAdd = ref(false)
  const hasGoods = ref(false)
  const goodsList = ref<any[]>([])
  const numMap = ref<any>({})
  
  // 显示添加数据弹出框
  const openAddDialog = () => {
    showAdd.value = true
  }
  
  // 关闭添加数据弹出框
  const closeAddDialog = () => {
    showAdd.value = false
  }

  const getTotalPrice = computed(() => {
    let total = 0
    goodsList.value.forEach(item => {
      const itemTotal = precisionMultiply(item.price || 0, numMap.value[item.id] || 0)
      total = precisionAdd(total, itemTotal)
    })
    return total
  })

  const getSubtotal = (item: any) => {
    return precisionMultiply(item.price || 0, numMap.value[item.id] || 0)
  }
  
  // 切换添加数据弹出框状态
  const toggleAddDialog = () => {
    showAdd.value = !showAdd.value
  }

  const clearGoods = () => {
    goodsList.value = []
    numMap.value = {}
  }

  const addGoods = (goods: any, num = 1) => {
    // goodsList.value.push(goods)
    // numMap.value[goods.id] = 1
    if(numMap.value[goods.id]){
      numMap.value[goods.id] = numMap.value[goods.id] + num
    }
    else{
      numMap.value[goods.id] = num;
      goodsList.value.push(goods)
    }
  }

  // 初始化 numMap，确保所有商品都有对应的数量
  const initData = () => {
    goodsList.value = []
    numMap.value = {}
    showAdd.value = false
    hasGoods.value = false
    // goodsList.value.forEach(item => {
    //   if (numMap.value[item.id] === undefined) {
    //     numMap.value[item.id] = 1
    //   }
    // })
  }

  return {
    getTotalPrice,
    getSubtotal,
    goodsList,
    numMap,
    clearGoods,
    hasGoods,
    showAdd,
    addGoods,
    initData,
    openAddDialog,
    closeAddDialog,
    toggleAddDialog,
  }
}) 